package com.ks.phone.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.google.gson.Gson;
import com.ks.basictools.ActivityManager;
import com.ks.basictools.BaseActivity;
import com.ks.basictools.utils.DisplayUtils;
import com.ks.basictools.utils.ToastUtils;
import com.ks.phone.R;
import com.ks.phone.UserManager;
import com.ks.phone.responseBean.CodeResponse;
import com.ks.phone.responseBean.UserResponse;
import com.ks.phone.constant.Constants;
import com.ks.phone.databinding.ActivityLoginBinding;
import com.ks.phone.manager.PreferenceManager;
import com.ks.phone.utils.NetworkUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.XHttpSDK;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity {

    private ActivityLoginBinding mBinding;
    private CountDownTimer countDownTimer;
    private String oldPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        mBinding.setActivity(this);
        start();
    }

    private void start() {
        initView();
        initListener();
    }

    private void initView() {
        /*设置文字间距*/
        mBinding.rb1.setChecked(PreferenceManager.getInstance().getAffiliate(LoginActivity.this).equals("赣州分公司"));
        mBinding.rb2.setChecked(PreferenceManager.getInstance().getAffiliate(LoginActivity.this).equals("上饶分公司"));
        mBinding.rb3.setChecked(PreferenceManager.getInstance().getAffiliate(LoginActivity.this).equals("上海分公司"));

        mBinding.rb1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.selector_radio, 0, 0, 0); // 设置选择框
        mBinding.rb1.setCompoundDrawablePadding(DisplayUtils.dp2px(LoginActivity.this, 10));
        mBinding.rb2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.selector_radio, 0, 0, 0); // 设置选择框
        mBinding.rb2.setCompoundDrawablePadding(DisplayUtils.dp2px(LoginActivity.this, 10));
        mBinding.rb3.setCompoundDrawablesWithIntrinsicBounds(R.drawable.selector_radio, 0, 0, 0); // 设置选择框
        mBinding.rb3.setCompoundDrawablePadding(DisplayUtils.dp2px(LoginActivity.this, 10));
    }

    private void initListener() {
        mBinding.rg.setOnCheckedChangeListener((group, checkedId) -> {
            View checked = mBinding.getRoot().findViewById(checkedId);
            if (mBinding.rb1.equals(checked)) {
                XHttpSDK.setBaseUrl(Constants.URL_BASE_ganzhou);
                PreferenceManager.getInstance().setAffiliate(LoginActivity.this,"赣州分公司");
            } else if (mBinding.rb2.equals(checked)) {
                XHttpSDK.setBaseUrl(Constants.URL_BASE_shangrao);
                PreferenceManager.getInstance().setAffiliate(LoginActivity.this,"上饶分公司");
            } else if (mBinding.rb3.equals(checked)) {
                XHttpSDK.setBaseUrl(Constants.URL_BASE_shanghai);
                PreferenceManager.getInstance().setAffiliate(LoginActivity.this,"上海分公司");
            }
        });
        mBinding.etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11 && !TextUtils.isEmpty(oldPhone)
                        && !oldPhone.equals(s.toString())) {
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                        countDownTimer = null;
                    }
                    mBinding.tvSendCode.setText("发送验证码");
                    mBinding.tvSendCode.setClickable(true);
                }
            }
        });
    }

    private void startTimer() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(60 * 1000, 1000) {
                public void onTick(long millisUntilFinished) {
                    // 每次倒计时间隔1秒，更新UI上的倒计时剩余时间
                    mBinding.tvSendCode.setText(millisUntilFinished / 1000 + "s");
                }

                public void onFinish() {
                    // 倒计时结束时执行的操作
                    mBinding.tvSendCode.setText("发送验证码");
                    mBinding.tvSendCode.setClickable(true);
                }
            };
        }
        countDownTimer.start();
    }

    public void onClick_sendCode(View ignoreV) {
        String account = mBinding.etAccount.getText().toString();
        if (TextUtils.isEmpty(account) || account.length() != 11) {
            ToastUtils.show(this, "请输入正确的手机号码");
            return;
        }

        Map<String, Object> param = new HashMap<>();
        param.put("phone", account);
        XHttp.post(Constants.URL_SEND_CODE)
                .params(param)
                .execute(new SimpleCallBack<CodeResponse>() {
                    @Override
                    public void onSuccess(CodeResponse response) {
                        Log.d("zhxk", "onSuccess: response = " + response);
                        oldPhone = account;
                        startTimer();
                        mBinding.tvSendCode.setClickable(false);
                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        Log.e("zhxk", "onError: e = " + e.getMessage());
                        ToastUtils.show(LoginActivity.this, e.getMessage());
                    }
                });
    }

    public void onClick_login(View ignoreV) {
        String account = mBinding.etAccount.getText().toString();
        String password = mBinding.etPassword.getText().toString();
        if (TextUtils.isEmpty(account) || account.length() != 11) {
            ToastUtils.show(this, "请输入正确的手机号码");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtils.show(this, "请输入验证码");
            return;
        }
        if (!NetworkUtils.isNetworkConnected(LoginActivity.this)) {
            ToastUtils.show(this, "请检查网络");
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("userAccount", account);
        param.put("password", password);
        XHttp.post(Constants.URL_LOGIN)
                .params(param)
                .execute(new SimpleCallBack<UserResponse>() {
                    @Override
                    public void onSuccess(UserResponse bean) {
                        Log.d("zhxk", "onSuccess: UserBean = " + bean);
                        UserManager.getInstance().saveUser(bean.getUser());
                        String json = new Gson().toJson(bean.getUser());
                        PreferenceManager.getInstance().setToken(LoginActivity.this, bean.getToken());
                        PreferenceManager.getInstance().setUser(LoginActivity.this, json);
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        ActivityManager.getInstance().finishActivity(LoginActivity.class);
                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        ToastUtils.show(LoginActivity.this, e.getMessage());
                    }
                });
    }
}